package dj.service.impl;

import org.apache.log4j.Logger;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import dj.Constant;
import dj.dao.BaseDao;
import dj.model.CompanyReport;
import dj.model.Tuser;
import dj.model.ZhebiaoXishu;
import dj.pageModel.PcompanyReport;
import dj.pageModel.Puser;
import dj.pageModel.PzhebiaoXishu;
import dj.service.CompanyReportService;
import dj.service.SmsService;
import dj.service.UserService;

@Service("companyReportService")
public class CompanyReportServiceImpl implements CompanyReportService {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(CompanyReportServiceImpl.class);

	private BaseDao<CompanyReport> companyDao;

	private UserService userService;

	private SmsService smsService;

	public BaseDao<CompanyReport> getCompanyDao() {
		return companyDao;
	}

	@Autowired
	public void setCompanyDao(BaseDao<CompanyReport> companyDao) {
		this.companyDao = companyDao;
	}

	public UserService getUserService() {
		return userService;
	}

	@Autowired
	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public SmsService getSmsService() {
		return smsService;
	}

	@Autowired
	public void setSmsService(SmsService smsService) {
		this.smsService = smsService;
	}

	public CompanyReport get(String id) {
		String hql = "from CompanyReport where id=:id";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		return companyDao.get(hql, params);
	}

	public void save(CompanyReport cr) {
		companyDao.save(cr);
	}

	public void update(CompanyReport cr) {
		companyDao.update(cr);
	}

	public void delete(CompanyReport cr) {
		companyDao.delete(cr);
	}

	public List<PcompanyReport> getCompanyReportTask(List<String> status, List<String> company, Map<String, Object> params, Map<String, String> conditions, int page, int rows, String order) {
		List<PcompanyReport> prs = new ArrayList<PcompanyReport>();
		List<CompanyReport> crs = new ArrayList<CompanyReport>();
		String hql = "from CompanyReport cr where 1=1";
		Map<String, Object> vparams = new HashMap<String, Object>();

		if (null != status && status.size() > 0) {
			hql += " and (";
			for (int i = 0; i < status.size(); i++) {
				if (i > 0) {
					hql += " or ";
				}
				hql += " status=:status" + i;
				vparams.put("status" + i, status.get(i));
			}
			hql += ")";
		}
		if (null != company && company.size() > 0) {
			hql += " and (";
			for (int i = 0; i < company.size(); i++) {
				if (i > 0) {
					hql += " or ";
				}
				hql += " userid=:userid" + i;
				vparams.put("userid" + i, company.get(i));
			}
			hql += ")";
		}
		if (null != params && params.size() > 0) {
			for (String key : params.keySet()) {
				String valueKey = key.substring(key.indexOf(".") + 1);
				hql += " and " + key + " " + conditions.get(key) + ":" + valueKey;
				vparams.put(valueKey, params.get(key));
			}
			if (null != order && !"".equals(order.trim())) {
				hql += " " + order;
			} else {
				hql += " order by taskmonth";
			}
			crs = companyDao.find(hql, vparams, page, rows);
		} else {
			if (null != order) {
				hql += " " + order;
			} else {
				hql += " order by taskmonth";
			}
			crs = companyDao.find(hql, page, rows);
		}

		if (null != crs && crs.size() > 0) {
			for (CompanyReport cr : crs) {
				PcompanyReport pr = new PcompanyReport();
				PzhebiaoXishu px = new PzhebiaoXishu();
				pr.setPzhebiaoXishu(px);

				BeanUtils.copyProperties(cr, pr);
				BeanUtils.copyProperties(cr.getZhebiaoXishu(), pr.getPzhebiaoXishu());
				prs.add(pr);
			}
		}

		return prs;
	}

	public long getCompanyReportTaskNum(List<String> status, List<String> company, Map<String, Object> params, Map<String, String> conditions) {
		String hql = "select count(cr) from CompanyReport cr where 1=1";
		Map<String, Object> vparams = new HashMap<String, Object>();
		Long num = null;
		if (null != status && status.size() > 0) {
			hql += " and (";
			for (int i = 0; i < status.size(); i++) {
				if (i > 0) {
					hql += " or ";
				}
				hql += " status=:status" + i;
				vparams.put("status" + i, status.get(i));
			}
			hql += ")";
		}
		if (null != company && company.size() > 0) {
			hql += " and (";
			for (int i = 0; i < company.size(); i++) {
				if (i > 0) {
					hql += " or ";
				}
				hql += " userid=:userid" + i;
				vparams.put("userid" + i, company.get(i));
			}
			hql += ")";
		}
		if (null != params && params.size() > 0) {
			for (String key : params.keySet()) {
				String valueKey = key.substring(key.indexOf(".") + 1);
				hql += " and " + key + " " + conditions.get(key) + ":" + valueKey;
				vparams.put(valueKey, params.get(key));
			}
			hql += " order by taskmonth";
			num = companyDao.getCount(hql, vparams);
		} else {
			num = companyDao.getCount(hql);
		}
		return num;
	}

	public void createReportTask(PcompanyReport pr, ZhebiaoXishu zx) {
		Puser loginUser = (Puser) ServletActionContext.getRequest().getSession().getAttribute(Constant.USER_SESSION);

		String[] companys = ServletActionContext.getRequest().getParameterValues("companys");

		for (String company : companys) {
			// 如果等于登录人员，继续
			Tuser user;
			if (loginUser.getId().equals(company)) {
				continue;
			} else {
				user = userService.getUserById(company);
				if (null == user || null == user.getId() || null == user.getName()) {
					continue;
				}
			}

			CompanyReport cr = new CompanyReport();
			cr.setId(UUID.randomUUID().toString());
			cr.setCreateDate(new Date());
			cr.setCreatorid(loginUser.getId());
			cr.setCreatorname(loginUser.getName());
			cr.setUserid(company);
			cr.setUsername(user.getName());
			cr.setStartDate(pr.getStartDate());
			cr.setEndDate(pr.getEndDate());
			cr.setZhebiaoXishu(zx);
			cr.setTaskmonth(pr.getTaskmonth());
			cr.setStatus(PcompanyReport.STRUTS_未填写);
			save(cr);
		}
	}

	public void deleteTasks(String[] ids) {
		if (null != ids) {
			String hql = "delete from CompanyReport where ";
			Map<String, Object> params = new HashMap<String, Object>();
			for (int x = 0; x < ids.length; x++) {
				String id = ids[x];
				if (x != 0) {
					hql += " or ";
				}
				hql += "id=:id" + x;
				params.put("id" + x, id);
			}
			companyDao.executeHql(hql, params);
		}
	}

	public void updateTaskDate(PcompanyReport pr) {
		String hql = "update CompanyReport set startDate=:startDate, endDate=:endDate where id=:id";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("startDate", pr.getStartDate());
		params.put("endDate", pr.getEndDate());
		params.put("id", pr.getId());

		companyDao.executeHql(hql, params);
	}

	public List<CompanyReport> getNotSubmitReport() throws Exception {
		Date date = new Date();
		Calendar c = Calendar.getInstance();
		c.setTime(date); // 设置当前日期
		c.add(Calendar.DATE, 1); // 日期加1天
		date = c.getTime();

		String hql = "from CompanyReport where (status=:status0 or status=:status1 or status=:status2) and startDate<=:startDate";
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("status0", PcompanyReport.STRUTS_未填写);
		params.put("status1", PcompanyReport.STRUTS_未提交);
		params.put("status2", PcompanyReport.STRUTS_未通过);
		params.put("startDate", date);

		return companyDao.find(hql, params);
	}

	public void sendUrgeReportSms() throws Exception {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

		List<CompanyReport> crs = getNotSubmitReport();
		for (CompanyReport cr : crs) {
			Tuser user = userService.getUserById(cr.getUserid());
			String phone = "";
			try {
				phone = user.getUserExtends().iterator().next().getPhone();
			} catch (Exception e) {
				logger.error("没有找到企业“" + user.getName() + "” 的联系电话！");
			}
			if (!"".equals(phone)) {
				List<String> phones = new ArrayList<String>();
				phones.add(phone);

				String msg = "您有一个开始日期：" + sdf.format(cr.getStartDate()) + "，结束日期：" + sdf.format(cr.getEndDate()) + " 的任务尚未提交，请尽快提交！";
				smsService.sendSms(phones, msg, cr.getUserid(), cr.getId());
			}
		}
	}

}
